<template>
  <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose :title="title" :height="400" :width="1000" @ok="handleSubmit" @cancel="handleCancel">
      <div style="display:flex;">
        <!-- <div style="width:700px;padding:60px 20px;border-right: 1px solid #e5e7eb;"> -->
        <div>
            <BasicForm  @register="registerForm">
                <template #channelSlot="{ model, field }">
                    <a-select 
                       v-model:value="model[field]" @change="channelChange"
                        style="width: 180px" :fieldNames="{label:'name',value:'id' }"
                        :options="channelOptions"
                    >
                    </a-select>
                </template>
                <template #ruleSlot="{ model, field }">
                    <a-select
                       v-model:value="model[field]"
                        style="width: 180px" :fieldNames="{label:'ruleName',value:'ruleId' }"
                        :options="ruleOptions"
                    >
                    </a-select>
                </template>
                 <template #groupIdListSlot="{model,field}">
                    <JDictSelectTag v-model:value="model[field]" @change="groupIdListChange" dictCode="ac_group,group_name,id" mode="tags"></JDictSelectTag>
                </template>
                <template #personSlot="{model,field}">
                    <!-- <JSelectGroupPerson v-model:value="model[field]" :groupId="groupIdList"></JSelectGroupPerson> -->
                    <JSelectGroupPerson v-model:value="personIds" :groupId="groupIdList" ></JSelectGroupPerson>
                </template>
            </BasicForm>
        </div>
        <!-- <div style="width:800px;">
            <BasicTable @register="registerTable" :rowSelection="rowSelection">
            </BasicTable>
        </div> -->
      </div>
     
  </BasicModal>
</template>

<script lang="ts" setup>
    import {ref, computed, unref, reactive} from 'vue';
    import { toRaw } from '@vue/reactivity';
    import {BasicTable, useTable, TableAction} from '/@/components/Table';
    import {BasicModal, useModalInner} from '/@/components/Modal';
    import {BasicForm, useForm} from '/@/components/Form/index';
    import { useListPage } from '/@/hooks/system/useListPage'
    import {formSchema,deviceColumns,deviceSearchFormSchema} from '../generalAuthorization.data';
    import {saveOrUpdate,deviceList,ruleList,addRuleApi} from '../generalAuthorization.api';
    import { message } from 'ant-design-vue';
    import { number } from 'vue-types';
    import {list} from "@/views/channel/channel/SsChannel.api";
    import JSelectGroupPerson from '@/components/Form/src/jeecg/components/JSelectGroupPerson.vue'
    import JDictSelectTag from '@/components/Form/src/jeecg/components/JDictSelectTag.vue'
    // Emits声明
    const emit = defineEmits(['register','success']);
    const isUpdate = ref(false);

    let ruleOptions= ref([])
    let channelOptions= ref([])
    let groupIdList = ref('')
    let personIds = ref('')
    const { prefixCls,tableContext,onExportXls,onImportXls } = useListPage({
      tableProps:{
           title: '选择设备',
           api: deviceList,
           columns :deviceColumns,
           canResize:false,
           showActionColumn: false,
           formConfig: {
              labelWidth: 65,
              schemas: deviceSearchFormSchema,
              autoSubmitOnEnter:true,
              showAdvancedButton:true,
              fieldMapToNumber: [
              ],
              fieldMapToTime: [
              ],
            },
           actionColumn: {
               width: 120,
               fixed:'right'
            },
      },
     
  })
  
  const [registerTable, {reload,getForm},{ rowSelection, selectedRowKeys }] = tableContext

    //表单配置
    const [registerForm, {setProps,resetFields, setFieldsValue, validate}] = useForm({
        labelWidth: 150,
        schemas: formSchema,
        showActionButtonGroup: false,
        baseColProps: {span: 12}
    });
    //表单赋值
    const [registerModal, {setModalProps, closeModal}] = useModalInner(async (data) => {
        //重置表单
        personIds.value = ''
        groupIdList.value = ''
        await resetFields();
        getRuleList();
        getChannelList();
        setModalProps({confirmLoading: false,showCancelBtn:!!data?.showFooter,showOkBtn:!!data?.showFooter});
        isUpdate.value = !!data?.isUpdate;
        if (unref(isUpdate)) {
            //表单赋值
            await setFieldsValue({
                ...data.record,
            });
        }
        // 隐藏底部时禁用整个表单
       setProps({ disabled: !data?.showFooter })
    });
    async function groupIdListChange(e){
        // console.log(e);
        groupIdList.value = e? e.join(','): ''
        personIds.value = ''
            // setFieldsValue({
            //     personIds : ''
            // })
          
    }
    //设置标题
    const title = computed(() => (!unref(isUpdate) ? '批量授权' : '授权'));
    function JSelectPersonUpdate(e){
        console.log(e);
    }
    //表单提交事件
    async function handleSubmit(v) {
        try {
            let values = await validate();
            // let selectIds = toRaw(rowSelection.selectedRowKeys)
            // console.log(selectIds);
            // if(selectIds.length==0) return message.warning('请先选择设备');
            // values.deviceList = selectIds
            values.groupIdList = values.groupIdList.split(',')
            values.personIds = personIds.value
            console.log(values);
            await addRuleApi(values)
            setModalProps({confirmLoading: true});

            //提交表单
            //关闭弹窗
            closeModal();
            //刷新列表
            emit('success');
        } finally {
            setModalProps({confirmLoading: false});
        }
    }
    function handleCancel(){
        console.log(111);
        personIds.value = ''
        resetFields()
        setFieldsValue({
                personIds : ''
            })
    }
    async function channelChange(id){
        console.log(id);
        await setFieldsValue({
            ruleId:''
        })
        getRuleList(id)
    }
    function getRuleList(id){
       ruleList({
        channelId: id ? id:''
       }).then(res=>{
        ruleOptions.value = res
       })
    }
    function getChannelList(){
       list({
       }).then(res=>{
         channelOptions.value = res.records
       })
    }
</script>

<style lang="less" scoped>
	/** 时间和数字输入框样式 */
  :deep(.ant-input-number){
		width: 100%
	}

	:deep(.ant-calendar-picker){
		width: 100%
	}
</style>
